package 树.遍历;

import 抽象数据类型.TreeNode;

import java.util.LinkedList;
import java.util.Stack;

public class BackTraverse {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.left.right = new TreeNode(8);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        root.right.right.right = new TreeNode(9);
        backOrderTraverse(root, list);
        for (Object o : list) {
            System.out.println(((TreeNode) o).getVal());
        }
        backTraverse(root);

    }

    public static void backTraverse(TreeNode root) {
        System.out.println("\n后序遍历");
        Stack<TreeNode> stack = new Stack<>();
        while (true) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            while (!stack.empty() && (stack.peek().right == root)) {
                root = stack.pop();
                System.out.print(root.val);
            }
            if (!stack.empty()) {
                root = stack.peek().right;
            }
            else  {
                break;
            }
        }
        System.out.println();
    }

    private static void backOrderTraverse(TreeNode node, LinkedList list) {
        if (node == null) {
            return;
        }
        Stack stack = new Stack();

        TreeNode root = node;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                if (root.getLeft() != null) {
                    root = root.getLeft();
                } else {
                    root = root.getRight();
                }
            }
            if (!stack.isEmpty()) {
                root = (TreeNode) stack.pop();
                list.add(root);

            }
            //满足条件时，说明栈顶根节点右子树已访问，应出栈访问之
            while (!stack.isEmpty() && ((TreeNode) stack.peek()).getRight() == root) {
                root = (TreeNode) stack.pop();
                list.add(root);
            }
            //转向栈顶根结点的右子树继续后序遍历
            if (!stack.isEmpty()) {
                root = ((TreeNode) stack.peek()).getRight();
            } else {
                root = null;
            }

        }


    }

}
